﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SurfaceAd.Common;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

/**
 * 创建时间：2014/9/23 11:10:55
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Assistant
{
    public sealed class NavigatorHelper
    {
        /// <summary>
        /// 根据navigateKey获取值
        /// <para>用法：await NavigatorHelper.GetNavigateValueByKeyAsync(WebViewNavigatorKey.appCodeName.ToString());</para>
        /// </summary>
        /// <param name="navigateKey"></param>
        /// <returns></returns>
        public static IAsyncOperation<String> GetNavigateValueByKeyAsync(String navigateKey)
        {
            return GetNavigateValueByKey(navigateKey).AsAsyncOperation();
        }

        private async static Task<String> GetNavigateValueByKey(String navigateKey)
        {
            String result = "UnKnow";
            String script = Constants.NavigatorKeys[navigateKey];
            try
            {
                var w = new WebView();
                w.NavigateToString("<html />");
                NotifyEventHandler h = null;
                h = (s, e) =>
                {
                    try
                    {
                        //5.0 (Windows Phone 8.1; ARM; Trident/7.0; Touch; WebView/2.0; rv:11.0; IEMobile/11.0; Microsoft; Virtual) like Gecko
                        //var match = Regex.Match(e.Value, @"Windows\s+NT\s+\d+(\.\d+)?");
                        //if (match.Success)
                        //result = match.Value; ;
                        result = e.Value;
                    }
                    catch (Exception err) { LogHelper.LogError(err.ToString(), typeof(NavigatorHelper), "GetNavigateValueByKey.ScriptNotify"); }
                    finally { w.ScriptNotify -= h; }
                };
                w.ScriptNotify += h;
                await w.InvokeScriptAsync("execScript", new[] { string.Format("window.external.notify({0}); ", script) });
            }
            catch (Exception err)
            {
                LogHelper.LogError(navigateKey + ":" + script + Environment.NewLine + err.ToString(), typeof(NavigatorHelper), "GetNavigateValueByKey");
            }
            return result;
        }
    }
}
